package com.badibadi.mytools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;

public class HtmlUtils {
	// context.getApplicationContext().getFilesDir().getAbsolutePath()
	private static final String TAG = "NetworkImageGetter";
	TextView mTvThree;
	String htmlThree;// 包含html的内容
	int TextSize = -1;// =DisplayUtil.dip2px(, dipValue);
	/** 网络图片Getter */
	private NetworkImageGetter mImageGetter;
	Context context;
	// 如果是editText；
	EditText editText;
	int flags = 0;// 0显示TextView 1显示EditText
 
	public HtmlUtils(Context context, TextView mTextView, String content) {
		this.context = context;
		mTvThree = mTextView;
		htmlThree = content;
		mImageGetter = new NetworkImageGetter();
		TextSize = DisplayUtil.dip2px(context, 20);// 默认是30
	}

	public HtmlUtils(Context context, TextView mTextView, String content,
			int TextSize) {
		this.context = context;
		this.TextSize = TextSize;
		mTvThree = mTextView;
		htmlThree = content;
		mImageGetter = new NetworkImageGetter();
	}

	public HtmlUtils(Context context, EditText mEditText, String content) {
		this.context = context;
		this.editText = mEditText;
		htmlThree = content;
		mImageGetter = new NetworkImageGetter();
		TextSize = DisplayUtil.dip2px(context, 30);// 默认是30
	}

	public HtmlUtils(Context context, EditText mEditText, String content,
			int TextSize) {
		this.context = context;
		this.editText = mEditText;
		htmlThree = content;
		mImageGetter = new NetworkImageGetter();
		this.TextSize = TextSize;// 默认是30
	}

	public void showEditText() {
		flags = 1;
		editText.setText(Html.fromHtml(htmlThree, mImageGetter, null),
				TextView.BufferType.SPANNABLE);
	}

	public void showTextView() {
		flags = 0;
		mTvThree.setText(Html.fromHtml(htmlThree, mImageGetter, null),
				TextView.BufferType.SPANNABLE);
	}

	/**
	 * 本地图片
	 * 
	 * @author Susie
	 */
	private final class LocalImageGetter implements Html.ImageGetter {

		@Override
		public Drawable getDrawable(String source) {
			// 获取本地图片
			Drawable drawable = Drawable.createFromPath(source);
			// 必须设为图片的边际,不然TextView显示不出图片
			// drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
			// drawable.getIntrinsicHeight());

			if (TextSize == -1) {
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight());
			} else {
				drawable.setBounds(0, 0, TextSize, TextSize);
			}

			// 将其返回
			return drawable;
		}
	}

	/**
	 * 网络图片
	 * 
	 * @author Susie
	 */
	private final class NetworkImageGetter implements Html.ImageGetter {

		@Override
		public Drawable getDrawable(String source) {
			Drawable drawable = null;

			String path = MD5.getMD5(source);
			// 封装路径
			// File file = new File(Environment.getExternalStorageDirectory(),
			// path);
			File file = new File(context.getApplicationContext().getFilesDir()
					.getAbsolutePath(), path);

			//    
			//    
			// 判断是否以http开头
			if (source.startsWith("http")) {
				// 判断路径是否存在
				if (file.exists()) {
					// 存在即获取drawable
					// drawable =
					// Drawable.createFromPath(file.getAbsolutePath());
					// if(TextSize<=80)//这是怕图片过大
					// path=ImageTools.ReducePictureQuality(path, path);
//					FileInputStream in = null;
//					try {
//						in = new FileInputStream(file.getAbsolutePath());
//					} catch (FileNotFoundException e) {
//						// TODO Auto-generated catch block
//						   
//					} finally {
//
//					}
//					if (in != null) {
						// BitmapFactory.Options options=new
						// BitmapFactory.Options();
						// options.inSampleSize=10;
						Bitmap bmp = ImageTools.getBitmapFromFile(file,
								TextSize, TextSize);
						// Bitmap
						// bmp=Bitmap.createBitmap(file.getAbsolutePath(),
						// TextSize, TextSize, options);

						drawable = ImageTools.bitmapToDrawable(bmp);

						// drawable=Drawable.createFromStream(in, "src");
//					}
					// else
					// {
					// drawable =
					// Drawable.createFromPath(file.getAbsolutePath());
					// }

//					   
//							"file.getAbsolutePath()==>"
//									+ file.getAbsolutePath());
					// drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					// drawable.getIntrinsicHeight());
					if (drawable != null) {
						if (TextSize == -1) {
							drawable.setBounds(0, 0,
									drawable.getIntrinsicWidth(),
									drawable.getIntrinsicHeight());
						} else {
							drawable.setBounds(0, 0, TextSize, TextSize);
						}
					}
				} else {
					// 不存在即开启异步任务加载网络图片
					AsyncLoadNetworkPic networkPic = new AsyncLoadNetworkPic();
					networkPic.execute(source);
				}
			}
			return drawable;
		}
	}

	/**
	 * 加载网络图片异步类
	 * 
	 * @author Susie
	 */
	private final class AsyncLoadNetworkPic extends
			AsyncTask<String, Integer, Void> {

		@Override
		protected Void doInBackground(String... params) {
			// 加载网络图片
			loadNetPic(params);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			// 当执行完成后再次为其设置一次
			if (flags == 0) {
				mTvThree.setText(Html.fromHtml(htmlThree, mImageGetter, null),
						TextView.BufferType.SPANNABLE);
			} else {
				editText.setText(Html.fromHtml(htmlThree, mImageGetter, null),
						TextView.BufferType.SPANNABLE);
			}

		}

		/** 加载网络图片 */
		private void loadNetPic(String... params) {
			String path = params[0];

			// File file = new File(Environment.getExternalStorageDirectory(),
			// MD5.getMD5(path));
			File file = new File(context.getApplicationContext().getFilesDir()
					.getAbsolutePath(), MD5.getMD5(path));
			InputStream in = null;

			FileOutputStream out = null;

			try {
				URL url = new URL(path);

				HttpURLConnection connUrl = (HttpURLConnection) url
						.openConnection();

				connUrl.setConnectTimeout(5000);

				connUrl.setRequestMethod("GET");

				if (connUrl.getResponseCode() == 200) {

					in = connUrl.getInputStream();

					out = new FileOutputStream(file);

					byte[] buffer = new byte[1024];

					int len;

					while ((len = in.read(buffer)) != -1) {
						out.write(buffer, 0, len);
					}
				} else {
//					   
				}
			} catch (Exception e) {
				   
			} finally {

				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						   
					}
				}
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						   
					}
				}
			}
		}
	}

}
